package com.ews.onlineexchange.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ResponseHeaderFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		httpResponse.setHeader("Access-Control-Allow-Origin", "*");
		httpResponse.addHeader("Access-Control-Allow-Credentials", "true");
		httpResponse.addHeader("Access-Control-Allow-Headers",
				"Origin, No-Cache, X-Requested-With, If-Modified-Since, Cookie, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, signature, replayId, token, ajaxrequest, Authorization, JSESSIONID");
		httpResponse.addHeader("Access-Control-Allow-Methods", "POST, PUT, GET, DELETE, OPTIONS, HEAD, TRACE, CONNECT");
		if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
			response.getWriter().write("OK");
			return;
		}
		if(!((HttpServletRequest) request).isRequestedSessionIdFromCookie()){ 
			 httpResponse.setHeader("JSESSIONID", ((HttpServletRequest) request).getSession().getId()); 
			} 
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
